//
//  VVNetworkTools.swift
//  Weibo
//
//  Created by 王惠平 on 2017/3/29.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit
import AFNetworking

//网络请求的类型,在swift里面枚举是可以指定类型
enum RequestType: Int {
    
    //get请求
    case get = 0
    
    //post请求
    case post = 1
}

class VVNetworkTools: AFHTTPSessionManager {

    //单例的全局访问点
    static let sharedTools: VVNetworkTools = {
        
        let tools = VVNetworkTools()
        
        //添加afn可以接收数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
     fileprivate func request(type: RequestType,urlStr: String,params: Any?, finishCallBack: @escaping (Any?,Error?)->() ) {
        
        
        if type == .post {
            
            //AFN的请求方法
            post(urlStr, parameters: params, progress: nil, success: { (_, response) in
                
                //成功的回调
                finishCallBack(response, nil)
                
            }, failure: { (_, Error) in
                
                //失败的回调
                finishCallBack(nil, Error)
            })
       
        } else {
            
            get(urlStr, parameters: params, progress: nil, success: { (_, response) in
                
                //成功的回调
                finishCallBack(response, nil)
                
            }, failure: { (_, Error) in
                
                //失败的回调
                finishCallBack(nil, Error)
                
            })
            
        }
    
    }
    
}
//首页相关接口
extension VVNetworkTools {

    //发送带图片的微博
    func sendWeiboMessage(accessToken: String, status: String, pic: UIImage, finishCallBack:@escaping (Any?, Error?)->()) {
        
        //请求地址
        let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        //请求参数
        let params = [
            
            "access_token": accessToken,
            "status": status
            
        ]
        
        // compressionQuality 图片的质量系数,系数越大图片对应的二进制数据越大, 如果对图片质量要求不高,可以把系统设置小一点
        let imageData = UIImageJPEGRepresentation(pic, 0.5)!
        
        //try! imageData.write(to: URL(fileURLWithPath: "/Users/wanghuiping/Desktop/1.jpg"))
        
        post(urlStr, parameters: params, constructingBodyWith: { (formData) in
            
            formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
        }, progress: nil, success: { (_, response) in
            
            finishCallBack(response,nil)
            
        }) { (_, error) in
            
            finishCallBack(nil,error)
        }
        
    }
    
    //发送文字微博
    func sendWeiboMessage(accessToken: String, status: String, finishCallBack:@escaping (Any?, Error?)->()) {
        
        //请求地址
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        
        //请求参数
        let params = [
        
            "access_token": accessToken,
            "status": status
        
        ]
        
        //发送网络请求
        request(type: .post, urlStr: urlStr, params: params, finishCallBack: finishCallBack)
    }
    
    func requestHomeData(accessToken: String, maxId: Int64 = 0,  sinceId: Int64 = 0, finishCallBack: @escaping (Any?, Error?)->()) {
        
        
        //请求地址
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        print(urlStr + "?access_token=\(accessToken)")
        //请求参数
        let params: [String: Any] = [
            
            "access_token": accessToken,
            "max_id": maxId,
            "since_id": sinceId
            ]
        
        //发送网络请求
        request(type: .get, urlStr: urlStr, params: params, finishCallBack: finishCallBack)
    }
    
    
}

//OAuth登录相关接口
extension VVNetworkTools {
    
    // 通过code(授权码)获取accesstoken
    func requestAccessToken(code: String,finishCallBack: @escaping (Any?, Error?)->()) {
        
        //请求地址
        let urlStr = "https://api.weibo.com/oauth2/access_token"
    
        //请求参数
        let params: [String: Any] = [
        
        "client_id": AppKey,
        "client_secret": AppSecret,
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri":uri
        
        
        ]
        
        //发送网络请求
        request(type: .post, urlStr: urlStr, params: params, finishCallBack: finishCallBack)
        
    }
   
    // 通过accessToken和uid获取用户信息
    func requestUserInfo(accessToken: String,uid: Int64, finishCallBack:@escaping (Any?, Error?)->()) {
        
        //请求地址
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        print(urlStr + "?access_token=\(accessToken)&uid=\(uid)")
        
        //请求参数
        let params: [String: Any] = [
        
        "access_token": accessToken,
        
        "uid": uid
        
        ]
        
        //发送网络请求
        request(type: .get, urlStr: urlStr, params: params, finishCallBack: finishCallBack)
    }
    
    
    
    
}
